﻿using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.TextManager.Interop;
using static System.Net.Mime.MediaTypeNames;

namespace ParameterFormat
{
    [Command(PackageIds.MyCommand)]
    internal sealed class MyCommand : BaseCommand<MyCommand>
    {
        protected override async Task ExecuteAsync(OleMenuCmdEventArgs e)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            var textManager = await ServiceProvider.GetGlobalServiceAsync(typeof(SVsTextManager)) as IVsTextManager2;
            IVsTextView textView;
            textManager.GetActiveView2(1, null, (uint)_VIEWFRAMETYPE.vftCodeWindow, out textView);


            var componentModel = await ServiceProvider.GetGlobalServiceAsync(typeof(SComponentModel)) as IComponentModel;
            var editorAdapter = componentModel.GetService<IVsEditorAdaptersFactoryService>();
            var wpfTextView = editorAdapter.GetWpfTextView(textView);


            if (wpfTextView == null) return;

            var selection = wpfTextView.Selection;
            if (selection.IsEmpty) return;

            var selectedText = selection.StreamSelectionSpan.GetText();
            var formattedText = ParameterFormat(selectedText);

            wpfTextView.TextBuffer.Replace(selection.StreamSelectionSpan.SnapshotSpan, formattedText);
        }


        /// <summary>
        /// 格式化
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        private string ParameterFormat(string text)
        {
            // 查找函数参数列表
            int startIndex = text.IndexOf('(');
            int endIndex = text.LastIndexOf(')');


            if (startIndex == -1 || endIndex == -1)
                return text;

            string beforeParams = text.Substring(0, startIndex + 1);
            string parameters = text.Substring(startIndex + 1, endIndex - startIndex - 1);
            string afterParams = text.Substring(endIndex);

            // 分割参数
            var paramsList = parameters.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            // 格式化每个参数
            for (int i = 0; i < paramsList.Length; i++)
            {
                paramsList[i] = paramsList[i].Trim();
            }

            // 重新组合
            string formattedParams = string.Join(separator: ",\n    \t\t", paramsList);
            return $"{beforeParams}\n    \t\t{formattedParams}\n \t \t{afterParams}";

        }



        /*
        private string ReturnStr(
            string str1,
            string str2,
            string str3,
            string str4
            )
        {
            return str1 + str2 + str3 + str4;
        }*/
    }
}
